package pl.streamsoft.test.currency_buisness;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class NBPApi {

	private final static String FILES_LIST_REMOTE_PATH = "http://www.nbp.pl/kursy/xml/dir.txt";
	private final static String FILE_BASE_PATH = "http://www.nbp.pl/kursy/xml/";

	private List<String> fileNames;

	public NBPApi() {
		fileNames = new ArrayList<String>();
	}

	public String getFileName(Calendar forDate) {

		DateFormat dateFormatter = new SimpleDateFormat("yyMMdd");
		String pattern = "^a[0-9]{3}z"
				+ dateFormatter.format(forDate.getTime()) + "\\.xml$";

		for (String fileName : fileNames) {
			if (fileName.matches(pattern)) {
				return fileName;
			}
		}

		return null;
	}

	protected List<String> downloadFile(String ulr_path) throws IOException {
		List<String> result = new ArrayList<String>();
		URL url = new URL(ulr_path);

		InputStream stream = url.openStream();
		InputStreamReader streamReader = new InputStreamReader(stream);
		BufferedReader reader = new BufferedReader(streamReader);

		String line = "";
		while ((line = reader.readLine()) != null) {
			result.add(line);
		}
		return result;
	}

	public void downloadFileNamesList() throws IOException {

		List<String> lines = downloadFile(FILES_LIST_REMOTE_PATH);

		for (String line : lines) {
			if (line.startsWith("a")) {
				fileNames.add(line + ".xml");
			}
		}
	}

	public String downloadFileContent(Calendar forDate) throws IOException {
		String filePath = FILE_BASE_PATH + getFileName(forDate);
		String content = "";

		List<String> lines = downloadFile(filePath);

		for (String line : lines) {
			content += line;
		}

		return content;
	}

	public TabelaKursow parseXMLContent(String content) throws JAXBException {
		Reader reader = new StringReader(content);
		return parseXMLContent(reader);
	}

	public TabelaKursow parseXMLContent(Reader content) throws JAXBException {
		TabelaKursow result = null;

		JAXBContext context = JAXBContext.newInstance(TabelaKursow.class);
		Unmarshaller um = context.createUnmarshaller();
		result = (TabelaKursow) um.unmarshal(content);

		return result;
	}

	public void initialize() throws IOException {
		this.downloadFileNamesList();
	}

	public TabelaKursow getCurrencyTable(Calendar forDate) throws IOException,
			JAXBException {
		String content = downloadFileContent(new GregorianCalendar(2013, 05, 13));
		return parseXMLContent(content);
	}
}
